package kubayaxi.video.client.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import kubayaxi.video.client.service.IFileService;
import kubayaxi.video.mybatis.auto.dao.*;
import kubayaxi.video.mybatis.auto.model.*;
import kubayaxi.video.service.base.common.treadlocal.UserContent;
import kubayaxi.video.service.base.util.common.Asserts;
import kubayaxi.video.service.base.util.tengxun.TXFileUtil;
import kubayaxi.video.service.base.util.transaction.TransactionUtil;
import kubayaxi.video.service.base.util.video.VideoUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Map;

@Service
public class FileServiceImpl implements IFileService {

    @Resource
    private ChannelMapper channelMapper;
    @Resource
    private TXFileUtil txFileUtil;
    @Resource
    private BannerMapper bannerMapper;
    @Resource
    private VideoMapper videoMapper;
    @Resource
    private ConfMapper confMapper;
    @Resource
    private ClientUserMapper clientUserMapper;
    @Resource
    private TransactionUtil transactionUtil;

    /**
     * 视频上传
     */
    @Override
    public void videoUpload(MultipartFile videoFile, Long cId, String title, String desc) throws Exception {
        //判断用户参数是否给全
        Asserts.isNotNull(videoFile,"视频文件为空");
        Asserts.isNotNull(cId,"频道id为空");
        Asserts.isNotBlank(title,"视频标题为空");
        Channel channel = channelMapper.selectById(cId); //根据频道id获取频道信息
        Asserts.isNotNull(channel,"无此频道id频道"); //没有找到对应的频道信息
        Long uId = UserContent.get(); //获取当前登录用户id
        //获取数据库临时文件路径
        String tempFilePathKey = "temp_file_path";
        String tempFilePath = System.getProperty("user.dir") + confMapper.selectOne(new LambdaQueryWrapper<Conf>().eq(Conf::getKey, tempFilePathKey)).getValue();
        //上传视频
        String videoPrePath = "lin/"+channel.getPath()+"video/";
        String videoUrl = txFileUtil.upload(videoFile, videoPrePath); //调用腾讯云上传
        //调用FFmpeg解析视频信息，获取视频的分辨率，时长，第一帧图等信息
        Map<String, String> extract = VideoUtil.extract(videoUrl, tempFilePath);
        //上传封面
        String bannerPrePath = "lin/"+channel.getPath()+"banner/";
        String coverPath = extract.get("coverPath"); //获取封面路劲
        String duration = extract.get("duration").substring(3, 8); //获取时长
        String ratio = extract.get("ratio"); //获取分辨率
        String bannerUrl = txFileUtil.uploadFile(new File(coverPath),bannerPrePath); //调用腾讯上传
        //用完本地封面图片后就删了
        boolean delete = new File(coverPath).delete();
        Asserts.isTrue(delete,"删除本地封面失败");
        //通过事务保存封面、视频信息进数据库、更新用户动态数量
        boolean b = transactionUtil.transactional(() -> {
            //保存视频
            Video video = new Video(); //new视频对象
            video.setCId(channel.getId()); //设置频道id
            video.setUId(UserContent.get()); //设置用户id
            video.setCoverUrl(bannerUrl); //设置封面地址
            video.setUrl(videoUrl); //设置视频url地址
            video.setTitle(title); //设置视频标题
            video.setName(videoFile.getOriginalFilename()); //设置视频文件名字
            video.setDesc(desc); //设置视频描述
            video.setDuration(duration); //设置视频时长
            video.setMark(ratio); //设置分辨率
            int insert1 = videoMapper.insert(video); //插入视频信息
            //保存封面
            Banner banner = new Banner(); //new封面对象
            banner.setUrl(bannerUrl); //设置封面url
            banner.setRemark(title); //设置封面标题
            banner.setVId(video.getId()); //设置封面对应视频id
            int insert2 = bannerMapper.insert(banner); //插入封面图
            //更新用户动态数量
            int update = clientUserMapper.update(null, new LambdaUpdateWrapper<ClientUser>()
                    .eq(ClientUser::getId, uId).setSql("dynamic_num = dynamic_num + 1"));
            return insert1 == 1 && insert2 == 1 && update == 1;
        });
        //事务失败回退事务
        Asserts.isTrue(b,"更新数据库失败");
    }

    /**
     * 头像上传
     */
    @Override
    public String headUpload(MultipartFile headFile) {
        Asserts.isNotNull(headFile,"头像文件为空");
        String prePath = "lin/head/";
        String portraitUrl = txFileUtil.upload(headFile, prePath);
        return portraitUrl;
    }
}
